﻿using System;
using System.Collections.Generic;
using System.IO;

namespace BridgeWebSystemLib.Core.Util
{
    public static class JsonUtil
    {
        /// <summary>
        /// 使用Newtonsoft.Json序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string JsonSerializeObject(object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 使用Newtonsoft.Json反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="text"></param>
        /// <returns></returns>
        public static List<T> JsonDeserializeList<T>(string text)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>>(text);
        }
        /// <summary>
        /// 使用Newtonsoft.Json反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="text"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string text)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(text);
        }
        
        /// <summary>
        /// 读取JSON文件
        /// </summary>
        /// <param name="key">JSON文件中的key值</param>
        /// <returns>JSON文件中的value值</returns>
        public static string ReadJsonFile(string jsonPath, string key)
        {
            if (!File.Exists(jsonPath))
                throw new Exception(jsonPath + "未找到文件！");
            using (StreamReader file = File.OpenText(jsonPath))
            {
                using (Newtonsoft.Json.JsonTextReader reader = new Newtonsoft.Json.JsonTextReader(file))
                {
                    Newtonsoft.Json.Linq.JObject o = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JToken.ReadFrom(reader);
                    var value = o[key].ToString();
                    return value;
                }
            }
        }
        /// <summary>
        /// 读取JSON文件
        /// </summary>
        /// <param name="jsonPath"></param>
        /// <returns></returns>
        public static string ReadJsonFile(string jsonPath)
        {
            if (!File.Exists(jsonPath))
                throw new Exception(jsonPath + "未找到文件！");
            string strJson = "";
            using (StreamReader file = File.OpenText(jsonPath))
            {
                strJson = file.ReadToEnd();
            }
            return strJson;
        }
    }
}
